package com.chart.web.controller.chart;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.chart.chart.domian.WxGood;
import com.chart.chart.domian.vo.MailVo;
import com.chart.chart.service.IWxGoodService;
import com.chart.common.core.controller.BaseController;
import com.chart.common.core.domain.AjaxResult;
import com.chart.common.core.domain.entity.SysUser;
import com.chart.common.core.domain.model.LoginUser;
import com.chart.common.core.redis.RedisCache;
import com.chart.common.utils.MailUntils;
import com.chart.common.utils.SecurityUtils;
import com.chart.common.utils.StringUtils;
import com.chart.common.utils.wechat.WeChatUtils;
import com.chart.framework.web.service.TokenService;
import com.chart.system.service.ISysUserService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 图表
 *
 * @author chart
 */
@Slf4j
@RestController
@RequestMapping("/wechat")
public class WechatController extends BaseController {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private IWxGoodService wxGoodService;

    @Value("${aliyunMail.fromAddr}")
    private String fromAddr;

    @Value("${aliyunMail.toAddr}")
    private String toAddr;

    @Value("${wxpay.token}")
    private String TOKEN;

    @Autowired
    private ISysUserService userService;

    public static final String qcode = "手机号：";

    // private static final String TOKEN = "X4yZ7k9B3mVfD1nQ5tG8wL2pR78";
    //登录后进行绑定
    @ApiOperation("secondary二维码")
    //@GetMapping("/getSecondaryTicket")
    public Map getSecondaryTicket(String phoneNum) {
        SysUser user = sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getPhonenumber, phoneNum));
        Map ticket = WeChatUtils.getTicket(2, redisCache);
        redisCache.setCacheObject(ticket.get("ticket").toString() + "bind", user.getUserId(), 180, TimeUnit.SECONDS);
        return ticket;
    }

    //1  login    2  bind
    //注册时进行绑定
    @ApiOperation("bind二维码")
    @GetMapping("/getBindTicket")
    public Map getBindTicket(String phoneNum) {
        SysUser user = sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getPhonenumber, phoneNum));
        if (user == null) {
            return AjaxResult.error("用户不存在");
        }
        Map ticket = WeChatUtils.getTicket(2, redisCache);
        if (ticket == null) {
            return AjaxResult.error("ticket不存在");
        }
        redisCache.setCacheObject(ticket.get("ticket").toString() + "bind", user.getUserId(), 180, TimeUnit.SECONDS);
        return ticket;
    }


    //1  login    2  bind
    // 登录的二维码
    @ApiOperation("login二维码")
    @GetMapping("/getLoginTicket")
    public Map getLoginTicket() {
        Map ticket = WeChatUtils.getTicket(1, redisCache);
        return ticket;
    }


    /**
     * 检查用户是否绑定 0未绑定 1已绑定
     *
     * @return
     */
    @ApiOperation("检查绑定")
    @GetMapping("checkBind")
    public AjaxResult checkBind() {
        Long userId = SecurityUtils.getUserId();
        SysUser sysUser = sysUserService.queryById(userId);

        String openId = sysUser.getOpenId();
        System.out.println(openId);
        if (openId == null || openId.isEmpty()) {
            return AjaxResult.success(0);//未绑定
        } else {
            return AjaxResult.success(1);//绑定
        }
    }


    @PostMapping("/bind")
    public AjaxResult Bind(Integer isBind) {
        if (isBind == null || (isBind != 0 && isBind != 1)) {
            return AjaxResult.error("请输入0或者1");
        }
        Long userId = SecurityUtils.getUserId();
        SysUser sysUser = sysUserService.selectUserById(userId);

        if (sysUser == null) {
            return AjaxResult.error("用户不存在");
        }
        sysUser.setIsBind(isBind);
        sysUserService.updateById(sysUser);
        return AjaxResult.success();
    }


    @ApiOperation("检测扫码登录")
    @GetMapping("/checkLogin")
    public Map<String, Object> checkLogin(String ticket) {
        Map<String, Object> map = new HashMap<>();

        // 参数校验
        if (StringUtils.isEmpty(ticket)) {
            map.put("status", "error");
            map.put("message", "ticket为空，请重新请求！");
            return map;
        }
        log.info("/checkLogin接口入参的ticket={}", ticket);

        // 获取缓存中的值
        String cacheValue = redisCache.getCacheObject(ticket);
        if (ObjectUtils.isEmpty(cacheValue)) {
            map.put("status", "no_scan"); // 未扫码
            return map;
        }

        //检查当前字符串是否以指定的 前缀 开头
        if (cacheValue.startsWith("login_")) {
            // 获取 openId 去掉 cacheValue 前面的 "login_" 前缀，提取出有效的数据部分
            String openId = cacheValue.substring("login_".length());
            // 查询用户信息
            SysUser user = sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getOpenId, openId));


            if (user == null) {
                map.put("status", "error");
                map.put("message", "用户不存在！");
                return map;
            }

            LambdaUpdateWrapper<SysUser> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(SysUser::getOpenId, openId)
                    .set(SysUser::getLoginDate, new Date());
            boolean isUpdated = sysUserService.update(updateWrapper);
            if (isUpdated) {
                log.info("用户 openId={} 的登录时间已更新", openId);
            } else {
                log.warn("更新用户 openId={} 的登录时间失败", openId);
            }

            LoginUser loginUser = new LoginUser();
            loginUser.setUserId(user.getUserId());
            loginUser.setDeptId(user.getDeptId());
            loginUser.setUser(user);

            // 获取 token
            String token = tokenService.createToken(loginUser);

            // 返回已登录状态
            map.put("status", "login");
            map.put("token", token); // 返回 token
        } else if (cacheValue.startsWith("no_register_")) {
            String openId = cacheValue.substring("no_register_".length()); // 提取 openId
            map.put("status", "no_register"); // 未注册
            map.put("openId", openId); // 返回 openId
        } else {
            map.put("status", "unknown"); // 未知状态
        }

        return map;
    }


    /**
     * H5验证页面
     *
     * @param
     * @param
     * @throws IOException
     */
    @PostMapping("checkH5")
    public AjaxResult checkH5(String phonenumber, String code, String openId, String ticket) {
        // 参数校验
        if (StringUtils.isEmpty(phonenumber)) {
            return AjaxResult.error("手机号不能为空");
        }

        if (StringUtils.isEmpty(code)) {
            return AjaxResult.error("验证码不能为空");
        }

        if (StringUtils.isEmpty(openId)) {
            return AjaxResult.error("openId不能为空");
        }

        //验证码验证
        String codes = redisCache.getCacheObject(qcode + phonenumber).toString();
        if (org.apache.commons.lang3.ObjectUtils.isNotEmpty(codes) || codes != "0000") {
            if (!codes.equals(code)) {
                return AjaxResult.error("验证码错误");
            }
        }
        //已注册
        //手机号校验
        SysUser sysUser = userService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getPhonenumber, phonenumber));
        if (org.apache.commons.lang3.ObjectUtils.isNotEmpty(sysUser)) {

            //根据openid查询数据库
            SysUser sysUsers = userService.selectUserByOpenid(openId);
            //openid不为空 已绑定
            if (!ObjectUtils.isEmpty(sysUsers)) {

                if (sysUsers.getPhonenumber() != phonenumber) {
                    //该注册手机号已被其他微信号绑定!
                    // alreadyMessage(openId);
                    String alreadyMessage = "该注册手机号已被其他微信号绑定!";
                    return new AjaxResult(606, alreadyMessage, "操作成功");
                } else {
                    //公众号提示：您已通过身份验证，欢迎登录！
                    // passMessage(openId);
                    String passMessage = "您已通过身份验证，欢迎登录！";
                    return new AjaxResult(200, passMessage, "操作成功");
                }
                //未绑定 直接绑定 更新数据库
            } else {
                // 根据手机号更新openID字段
                LambdaUpdateWrapper<SysUser> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(SysUser::getPhonenumber, phonenumber)
                        .set(SysUser::getOpenId, openId);
                boolean update = userService.update(updateWrapper);

                if (update) {

                    redisCache.setCacheObject(ticket, "login_" + openId, 180, TimeUnit.SECONDS);
                    System.out.println("更新成功");
                } else {
                    System.out.println("更新失败");
                }
            }
            // 未注册
        } else {


            String passMessage = "抱歉，您还未注册，请先注册后再进行登录";
            return new AjaxResult(607, passMessage, "操作成功");
        }
        String passMessage = "您已通过身份验证，欢迎登录！";

        return new AjaxResult(200, passMessage, "操作成功");
    }


    //获取标签内容
    private String getElementTextContent(Document document, String tagName) {
        NodeList nodeList = document.getElementsByTagName(tagName);
        return nodeList.getLength() > 0 ? nodeList.item(0).getTextContent() : "";
    }

    private void sendTextMessage(HttpServletResponse response, String toUserName, String content, Document document) throws IOException {
        response.setContentType("text/xml;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.write("<xml><ToUserName><![CDATA[" + toUserName + "]]></ToUserName>\n" +
                "<FromUserName><![CDATA[" + getElementTextContent(document, "ToUserName") + "]]></FromUserName>\n" +
                "<CreateTime>" + System.currentTimeMillis() + "</CreateTime>\n" +
                "<MsgType><![CDATA[text]]></MsgType>\n" +
                "<Content><![CDATA[" + content + "]]></Content>\n" +
                "<MsgId>1234567890123456</MsgId>\n" +
                "</xml>");
        writer.flush();
        writer.close();
    }

    private void handleSubscribeEvent(Document document, HttpServletResponse response, String openId) throws IOException {
        String eventKey = getElementTextContent(document, "EventKey");
        SysUser sysUser = sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getOpenId, openId));
        if (StringUtils.isNotEmpty(eventKey)) {
            String ticket = getElementTextContent(document, "Ticket");
            if (StringUtils.isNotEmpty(ticket)) {
                if ("qrscene_bind".equals(eventKey)) {

                    if (ObjectUtils.isEmpty(sysUser)) {
                        String s = redisCache.getCacheObject(ticket + "bind").toString();
                        long userId = Long.parseLong(s);
                        SysUser user = sysUserService.getById(userId);
                        String notice = openId + "_" + "bind";
                        redisCache.setCacheObject(ticket, notice, 180, TimeUnit.SECONDS);
                        if (ObjectUtils.isEmpty(user.getOpenId())) {
                            user.setOpenId(openId);
                            user.setIsSubscribe(0);
                            user.setFreeOper(3);
                        }
                        sysUserService.saveOrUpdate(user);
                        sendTextMessage(response, openId, "欢迎使用TOPCHARTS，您已经获得3次免费导出，快去试试吧！", document);
                    } else {
                        sendTextMessage(response, openId, "微信号已经被绑定", document);
                    }
                } else if ("qrscene_login".equals(eventKey)) {
                    // 处理登录事件
                    if (!ObjectUtils.isEmpty(sysUser)) {
                        String notice = openId + "_" + "login";
                        if (!ObjectUtils.isEmpty(sysUser)) {
                            sysUser.setIsSubscribe(0);
                            sysUserService.saveOrUpdate(sysUser);
                        }
                        redisCache.setCacheObject(ticket, notice, 180, TimeUnit.SECONDS);
                        sendTextMessage(response, openId, "欢迎继续使用TOPCHARTS!", document);
                    } else {
                        sendTextMessage(response, openId, "请先进行注册并绑定微信", document);
                    }
                }
            }
        } else {
            // 处理其他订阅事件
            if (!ObjectUtils.isEmpty(sysUser)) {
                sysUser.setIsSubscribe(0);
                sysUserService.saveOrUpdate(sysUser);
            }
            sendTextMessage(response, openId, "你好！", document);
        }
    }

    private void handleUnsubscribeEvent(String openId) {
        SysUser sysUser = sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getOpenId, openId));
        if (sysUser != null) {
            sysUser.setIsSubscribe(1);
            sysUserService.saveOrUpdate(sysUser);
        }
        // 发送空白响应
        // 省略部分代码...
    }

    private void handleScanEvent(Document document, HttpServletResponse response, String openId) throws IOException {
        String eventKey = getElementTextContent(document, "EventKey");
        String ticket = getElementTextContent(document, "Ticket");
        SysUser sysUser = sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getOpenId, openId));

        if ("login".equals(eventKey)) {
            if (!ObjectUtils.isEmpty(sysUser)) {
                if (sysUser.getIsSubscribe() == 0) {
                    String notice = openId + "_" + "login";
                    redisCache.setCacheObject(ticket, notice, 180, TimeUnit.SECONDS);
                    sendTextMessage(response, openId, "欢迎回来TOPCHARTS！", document);
                }
            } else {
                String notice = openId + "_" + "noregister";
                redisCache.setCacheObject(ticket, notice, 180, TimeUnit.SECONDS);
                sendTextMessage(response, openId, "您尚未注册，请先完成注册", document);
            }
        } else if ("bind".equals(eventKey)) {
            if (!ObjectUtils.isEmpty(sysUser)) {
                sendTextMessage(response, openId, "微信号已经被绑定", document);
            } else {
                long userId = Long.parseLong(redisCache.getCacheObject(ticket + "bind").toString());
                SysUser user = sysUserService.getById(userId);
                String notice = openId + "_" + "bind";
                redisCache.setCacheObject(ticket, notice, 180, TimeUnit.SECONDS);
                if (ObjectUtils.isEmpty(user.getOpenId())) {
                    user.setOpenId(openId);
                    user.setIsSubscribe(0);
                    user.setFreeOper(3);
                }
                sysUserService.saveOrUpdate(user);
                sendTextMessage(response, openId, "欢迎使用TOPCHARTS，您已经获得3次免费导出，快去试试吧！", document);
            }
        }
        sendTextMessage(response, openId, "处理扫码事件的响应消息", document);
    }

    private void handleClickEvent(Document document, HttpServletResponse response, String openId) throws IOException {
        String eventKey = getElementTextContent(document, "EventKey");
        if ("V1001_GOOD".equals(eventKey)) {
            WxGood wxGood = wxGoodService.getOne(new LambdaQueryWrapper<WxGood>().eq(WxGood::getOpenId, openId));
            if (ObjectUtils.isEmpty(wxGood)) {
                WxGood good = new WxGood();
                good.setGoods(1);
                good.setOpenId(openId);
                wxGoodService.saveOrUpdate(good);
            } else {
                Integer goods = wxGood.getGoods();
                wxGood.setGoods(goods + 1);
                wxGoodService.saveOrUpdate(wxGood);
            }
            sendTextMessage(response, openId, "感谢您对我们的认可", document);
        }
    }


//    public void handleText(Document document, HttpServletResponse response) throws IOException {
//        response.setContentType("text/xml;charset=utf-8");
//        PrintWriter writer = response.getWriter();
//        writer.write("<xml><ToUserName><![CDATA[" + document.getElementsByTagName("FromUserName").item(0).getTextContent() + "]]></ToUserName>\n" +
//                "<FromUserName><![CDATA[" + document.getElementsByTagName("ToUserName").item(0).getTextContent() + "]]></FromUserName>\n" +
//                "<CreateTime>" + System.currentTimeMillis() + "</CreateTime>\n" +
//                "<MsgType><![CDATA[text]]></MsgType>\n" +
//                "<Content><![CDATA[如果遇到问题，请点击<a href=\"https://topcharts.chipshare.cn/#/feedback\">帮助</a>]]></Content>\n" +
//                "<MsgId>24461056606432712</MsgId>\n" +
//                "</xml>");
//        writer.flush();
//        writer.close();
//    }


    @ApiOperation("发送邮件")
    @PostMapping("/sendMail")
    public void sendMail(@RequestBody MailVo mailVo) {
        //	创建Session会话
        Session session = MailUntils.createSession();

//	创建邮件对象
        MimeMessage message = null;
        try {
            message = new MimeMessage(session);
            message.setSubject(mailVo.getSubject());
            message.setText(mailVo.getText());
            message.setSentDate(new Date());
            message.saveChanges();
            message.setFrom(new InternetAddress(fromAddr));
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(toAddr));
            //发送
            Transport.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }


//    public void handleEvent1(Document document, HttpServletResponse response) throws IOException {
//        String event = document.getElementsByTagName("Event").item(0).getTextContent();
//        String openId = document.getElementsByTagName("FromUserName").item(0).getTextContent();
//        switch (event) {
//            case "subscribe": //关注了
//                String eventKey1 = document.getElementsByTagName("EventKey").item(0).getTextContent();
//                response.setContentType("text/xml;charset=utf-8");
//                PrintWriter writer1 = response.getWriter();
//                if (!ObjectUtils.isEmpty(eventKey1)) {
//                    String ticket1 = document.getElementsByTagName("Ticket").item(0).getTextContent();
//                    if (!ObjectUtils.isEmpty(ticket1)) {
//                        if ("qrscene_bind".equals(eventKey1)) {
//                            SysUser sysUser1 = sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getOpenId, openId));
//                            if (ObjectUtils.isEmpty(sysUser1)) {
//                                String s = redisCache.getCacheObject(ticket1 + "bind").toString();
//                                long userId = Long.parseLong(s);
//                                SysUser user1 = sysUserService.getById(userId);
//                                String notice = openId + "_" + "bind";
//                                redisCache.setCacheObject(ticket1, notice, 180, TimeUnit.SECONDS);
//                                if (ObjectUtils.isEmpty(user1.getOpenId())) {
//                                    user1.setOpenId(openId);
//                                }
//                                sysUserService.saveOrUpdate(user1);
//                                writer1.write("<xml><ToUserName><![CDATA[" + document.getElementsByTagName("FromUserName").item(0).getTextContent() + "]]></ToUserName>\n" +
//                                        "<FromUserName><![CDATA[" + document.getElementsByTagName("ToUserName").item(0).getTextContent() + "]]></FromUserName>\n" +
//                                        "<CreateTime>" + System.currentTimeMillis() + "</CreateTime>\n" +
//                                        "<MsgType><![CDATA[text]]></MsgType>\n" +
//                                        "<Content><![CDATA[欢迎使用TOPCHARTS，您已经获得3次免费导出，快去试试吧！]]></Content>\n" +
//                                        "<MsgId>1234567890123456</MsgId>\n" +
//                                        "</xml>");
//                            } else {
//                                writer1.write("<xml><ToUserName><![CDATA[" + document.getElementsByTagName("FromUserName").item(0).getTextContent() + "]]></ToUserName>\n" +
//                                        "<FromUserName><![CDATA[" + document.getElementsByTagName("ToUserName").item(0).getTextContent() + "]]></FromUserName>\n" +
//                                        "<CreateTime>" + System.currentTimeMillis() + "</CreateTime>\n" +
//                                        "<MsgType><![CDATA[text]]></MsgType>\n" +
//                                        "<Content><![CDATA[微信号已经被绑定]]></Content>\n" +
//                                        "<MsgId>1234567890123456</MsgId>\n" +
//                                        "</xml>");
//                            }
//                        } else if ("qrscene_login".equals(eventKey1)) {
//                            writer1.write("<xml><ToUserName><![CDATA[" + document.getElementsByTagName("FromUserName").item(0).getTextContent() + "]]></ToUserName>\n" +
//                                    "<FromUserName><![CDATA[" + document.getElementsByTagName("ToUserName").item(0).getTextContent() + "]]></FromUserName>\n" +
//                                    "<CreateTime>" + System.currentTimeMillis() + "</CreateTime>\n" +
//                                    "<MsgType><![CDATA[text]]></MsgType>\n" +
//                                    "<Content><![CDATA[您尚未注册，请先完成注册]]></Content>\n" +
//                                    "<MsgId>1234567890123456</MsgId>\n" +
//                                    "</xml>");
//                        }
//                    }
//                }
//                SysUser sysUser2 = sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getOpenId, openId));
//                if (!ObjectUtils.isEmpty(sysUser2)) {
//                    if (ObjectUtils.isEmpty(sysUser2.getIsSubscribe())) {
//                        sysUser2.setFreeOper(3);
//                    }
//                    sysUser2.setIsSubscribe(0);
//                    sysUserService.saveOrUpdate(sysUser2);
//                } else {
//                    writer1.write("<xml><ToUserName><![CDATA[" + document.getElementsByTagName("FromUserName").item(0).getTextContent() + "]]></ToUserName>\n" +
//                            "<FromUserName><![CDATA[" + document.getElementsByTagName("ToUserName").item(0).getTextContent() + "]]></FromUserName>\n" +
//                            "<CreateTime>" + System.currentTimeMillis() + "</CreateTime>\n" +
//                            "<MsgType><![CDATA[text]]></MsgType>\n" +
//                            "<Content><![CDATA[你好！]]></Content>\n" +
//                            "<MsgId>1234567890123456</MsgId>\n" +
//                            "</xml>");
//                }
//
//                writer1.flush();
//                writer1.close();
//                break;
//            case "unsubscribe": //取关了
//                SysUser sysUser = sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getOpenId, openId));
//                if (!ObjectUtils.isEmpty(sysUser)) {
//                    sysUser.setIsSubscribe(1);
//                    sysUserService.saveOrUpdate(sysUser);
//                }
//                PrintWriter writer2 = response.getWriter();
//                writer2.write("");
//                writer2.flush();
//                writer2.close();
//                break;
//            case "SCAN": //扫码了
//                String ticket3 = document.getElementsByTagName("Ticket").item(0).getTextContent();
//                String eventKey3 = document.getElementsByTagName("EventKey").item(0).getTextContent();
//                SysUser sysUser3 = sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getOpenId, openId));
//                response.setContentType("text/xml;charset=utf-8");
//                PrintWriter writer3 = response.getWriter();
//                if ("login".equals(eventKey3)) {
//                    if (!ObjectUtils.isEmpty(sysUser3)) {
//                        if (sysUser3.getIsSubscribe() == 0) {
//                            String notice = openId + "_" + "login";
//                            redisCache.setCacheObject(ticket3, notice, 180, TimeUnit.SECONDS);
//                            writer3.write("<xml><ToUserName><![CDATA[" + document.getElementsByTagName("FromUserName").item(0).getTextContent() + "]]></ToUserName>\n" +
//                                    "<FromUserName><![CDATA[" + document.getElementsByTagName("ToUserName").item(0).getTextContent() + "]]></FromUserName>\n" +
//                                    "<CreateTime>" + System.currentTimeMillis() + "</CreateTime>\n" +
//                                    "<MsgType><![CDATA[text]]></MsgType>\n" +
//                                    "<Content><![CDATA[欢迎回来TOPCHARTS！]]></Content>\n" +
//                                    "<MsgId>1234567890123456</MsgId>\n" +
//                                    "</xml>");
//                        }
//                    } else {
//                        String notice = openId + "_" + "noregister";
//                        redisCache.setCacheObject(ticket3, notice, 180, TimeUnit.SECONDS);
//                        writer3.write("<xml><ToUserName><![CDATA[" + document.getElementsByTagName("FromUserName").item(0).getTextContent() + "]]></ToUserName>\n" +
//                                "<FromUserName><![CDATA[" + document.getElementsByTagName("ToUserName").item(0).getTextContent() + "]]></FromUserName>\n" +
//                                "<CreateTime>" + System.currentTimeMillis() + "</CreateTime>\n" +
//                                "<MsgType><![CDATA[text]]></MsgType>\n" +
//                                "<Content><![CDATA[您尚未注册，请先完成注册]]></Content>\n" +
//                                "<MsgId>1234567890123456</MsgId>\n" +
//                                "</xml>");
//                    }
//                } else if ("bind".equals(eventKey3)) {
//                    if (!ObjectUtils.isEmpty(sysUser3)) {
//                        writer3.write("<xml><ToUserName><![CDATA[" + document.getElementsByTagName("FromUserName").item(0).getTextContent() + "]]></ToUserName>\n" +
//                                "<FromUserName><![CDATA[" + document.getElementsByTagName("ToUserName").item(0).getTextContent() + "]]></FromUserName>\n" +
//                                "<CreateTime>" + System.currentTimeMillis() + "</CreateTime>\n" +
//                                "<MsgType><![CDATA[text]]></MsgType>\n" +
//                                "<Content><![CDATA[微信号已经被绑定]]></Content>\n" +
//                                "<MsgId>1234567890123456</MsgId>\n" +
//                                "</xml>");
//                    } else {
//                        long userId = Long.parseLong(redisCache.getCacheObject(ticket3 + "bind").toString());
//                        SysUser user3 = sysUserService.getById(userId);
//                        String notice = openId + "_" + "bind";
//                        redisCache.setCacheObject(ticket3, notice, 180, TimeUnit.SECONDS);
//                        if (ObjectUtils.isEmpty(user3.getOpenId())) {
//                            user3.setOpenId(openId);
//                            user3.setIsSubscribe(0);
//                            user3.setFreeOper(3);
//                        }
//                        sysUserService.saveOrUpdate(user3);
//                        writer3.write("<xml><ToUserName><![CDATA[" + document.getElementsByTagName("FromUserName").item(0).getTextContent() + "]]></ToUserName>\n" +
//                                "<FromUserName><![CDATA[" + document.getElementsByTagName("ToUserName").item(0).getTextContent() + "]]></FromUserName>\n" +
//                                "<CreateTime>" + System.currentTimeMillis() + "</CreateTime>\n" +
//                                "<MsgType><![CDATA[text]]></MsgType>\n" +
//                                "<Content><![CDATA[欢迎使用TOPCHARTS，您已经获得3次免费导出，快去试试吧！]]></Content>\n" +
//                                "<MsgId>1234567890123456</MsgId>\n" +
//                                "</xml>");
//                    }
//                }
//                writer3.flush();
//                writer3.close();
//                break;
//            case "CLICK": //点击了
//                String eventKey4 = document.getElementsByTagName("EventKey").item(0).getTextContent();
//                WxGood wxGood = wxGoodService.getOne(new LambdaQueryWrapper<WxGood>().eq(WxGood::getOpenId, openId));
//                if (ObjectUtils.isEmpty(wxGood)) {
//                    WxGood good = new WxGood();
//                    good.setGoods(1);
//                    good.setOpenId(openId);
//                    wxGoodService.saveOrUpdate(good);
//                } else {
//                    Integer goods = wxGood.getGoods();
//                    wxGood.setGoods(goods + 1);
//                    wxGoodService.saveOrUpdate(wxGood);
//                }
//                response.setContentType("text/xml;charset=utf-8");
//                PrintWriter writer4 = response.getWriter();
//                if (eventKey4.equals("V1001_GOOD")) {
//                    writer4.write("<xml><ToUserName><![CDATA[" + document.getElementsByTagName("FromUserName").item(0).getTextContent() + "]]></ToUserName>\n" +
//                            "<FromUserName><![CDATA[" + document.getElementsByTagName("ToUserName").item(0).getTextContent() + "]]></FromUserName>\n" +
//                            "<CreateTime>" + System.currentTimeMillis() + "</CreateTime>\n" +
//                            "<MsgType><![CDATA[text]]></MsgType>\n" +
//                            "<Content><![CDATA[感谢您对我们的认可]]></Content>\n" +
//                            "<MsgId>1234567890123456</MsgId>\n" +
//                            "</xml>");
//                }
//                writer4.flush();
//                writer4.close();
//                break;
//        }
//    }
//

}
